package org.example;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author weigang
 * @create 2022-11-02 17:37
 */
public class TTLDemo2 {
    // 使用TransmittableThreadLocal
    static TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService = TtlExecutors.getTtlExecutorService(executorService);  // 用TtlExecutors装饰线程池
        transmittableThreadLocal.set("i am a transmittable parent");
        executorService.execute((Runnable) () -> {
            System.out.println(transmittableThreadLocal.get());
            transmittableThreadLocal.set("i am a old transmittable parent");    // 子线程设置新的值
        });
        System.out.println(transmittableThreadLocal.get());
        TimeUnit.SECONDS.sleep(1);
        transmittableThreadLocal.set("i am a new transmittable parent"); // 主线程设置新的值
        executorService.execute((Runnable) () -> System.out.println(transmittableThreadLocal.get()));
        //    i am a transmittable parent
        //    i am a transmittable parent
        //    i am a new transmittable parent

    }


}
